package com.lm.leetcode.briefsummary;

import java.util.StringTokenizer;

/**
 * @Auther: Min.Liu
 * @Description:
 * 给定一个字符串s，你需要反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。
 *
 * 示例 1：
 * 输入：s = "Let's take LeetCode contest"
 * 输出："s'teL ekat edoCteeL tsetnoc"
 *
 * 示例 2:
 * 输入： s = "Mr Ding"
 * 输出："rM gniD"
 *
 * @Date: Created in 15:45 2025/5/12
 */
public class ReversezWordsDemo {
    public static void main(String[] args) {
        ReversezWordsDemo demo = new ReversezWordsDemo();
        String s = "Let's take LeetCode contest";
        String reverseWords = demo.reverseWords(s);
        System.out.println(reverseWords);
    }

    public String reverseWords2(String s) {
        s= s.replaceAll(" +"," ").trim();
        String[] strings = s.split(" ");
        StringBuilder sb= new StringBuilder();
        for (int i = 0; i <strings.length; i++) {
            char[] charArray = strings[i].toCharArray();
            for (int j = charArray.length; j > 0 ; j--) {
                sb.append(charArray[j-1]);
            }
            if (i!=strings.length-1) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    //局部反转
    public String reverseWords(String s) {
        s= s.replaceAll(" +"," ").trim();
        char[] charArray = s.toCharArray();
        //查找开始和结束位置 中间内容交换
        int start = 0;
        int end = 0;
        while(end<charArray.length){
            if(end==charArray.length-1||charArray[end+1]==' '){
                int m = start;int n = end;
                while(m<n){
                    char temp = charArray[m];
                    charArray[m++] = charArray[n];
                    charArray[n--] = temp;
                }
                start=end+2;
            }
            end++;
        }
        return new String(charArray);
    }
}
